﻿using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

namespace AirlineServer
{
    public class QueryCache
    {
        private const int CACHE_SIZE = 100;

        private class Item
        {
            public string Query { get; set; }

            public List<AirTravel> Result { get; set; }
        }

        private readonly Hashtable cache = new Hashtable(CACHE_SIZE);

        private readonly Queue<Item> queires = new Queue<Item>(CACHE_SIZE);

        [MethodImpl(MethodImplOptions.Synchronized)]
        public List<AirTravel> GetFromCache(string query)
        {
            var item = cache[query] as Item;
            return item != null ? item.Result : null;
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public void AddToCache(string query, List<AirTravel> result)
        {
            var item = new Item
            {
                Query = query,
                Result = result,
            };

            if (queires.Count >= CACHE_SIZE)
            {
                var oldest = queires.Dequeue();
                cache.Remove(oldest.Query);
            }

            cache.Add(query, item);
            queires.Enqueue(item);
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public void Clear()
        {
            cache.Clear();
            queires.Clear();
        }
    }
}
